<?php

namespace App\Http\Controllers;

use App\Exceptions\InvalidRequestException;
use App\Models\Category;
use App\Models\OrderItem;
use App\Models\Product;
use App\SearchBuilders\ProductSearchBuilder;
use App\Services\CategoryService;
use App\Services\ProductService;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;

class ProductsController extends Controller
{
    /**
     * 商品列表
     *
     * @param Request $request
     * @param CategoryService $categoryService
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request, CategoryService $categoryService)
    {
        $page = $request->input('page', 1);
        $perPage = 16;
         $data=[];
        if ($request->input('category_id') )
$category = Category::find($request->input('category_id') ); 
            
        if($search = $request->input('search', ''))
      $data[]=['title','like','%'.$search.'%'];
        
         $orderBy=['id','asc'];
        if ($order = $request->input('order', '')) {
            if (preg_match('/^(.+)_(asc|desc)$/', $order, $m)) {
                if (in_array($m[1], ['price', 'sold_count', 'rating'])) {
                    // 调用查询构造器的排序
                    
                    $orderBy=[$m[1],$m[2]];
                }
                
            }
        }

 
        $products = Product::query()
            ->where($data)
            ->orderBy($orderBy[0],$orderBy[1])
            ->get();

        // 返回一个 LengthAwarePaginator 对象
        

        return view(
            'products.index',
            [
                'products' => $products,
                'categories' => '',
                'category' => $category ?? null,
                
            ]
        );
    }

    /**
     * 商品详情
     *
     * @param Product $product
     * @param Request $request
     * @param ProductService $service
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws InvalidRequestException
     */
    public function show(Product $product, Request $request, ProductService $service)
    {
        // 判断商品是否已经上架，如果没有上架则抛出异常。
        if (!$product->on_sale) {
            throw new InvalidRequestException('商品未上架');
        }
        $favored = false;
        // 用户未登录时返回的是 null, 已登录时返回的是对应的用户对象
        if ($user = $request->user()) {
            // 当前用户已收藏的商品中搜索 id 为当前商品 id 的商品
            // boolval() 函数用于把值转为布尔值
            $favored = boolval($user->favorites()->find($product->id));
        }

        $reviews = OrderItem::query()
            ->with(['order.user', 'productSku'])    // 预先加载关联关系
            ->where('product_id', $product->id)
            ->whereNotNull('reviewed_at')   // 筛选出已评价的
            ->orderBy('reviewed_at', 'DESC')    // 按评价时间倒序
            ->limit(10) // 取出 10 条
            ->get();

        // 创建一个查询构造器，只搜索上架的商品，取搜索结果的前 4 个商品
        $builder = (new ProductSearchBuilder())->onSale()->paginate(4, 1);
        // 遍历当前商品的属性
        foreach ($product->properties as $property) {
            // 添加到 should 条件中
            $builder->propertyFilter($property->name, $property->value, 'should');
        }
        // 设置最少匹配一半属性
        $builder->minShouldMatch(ceil(count($product->properties) / 2));
        $params = $builder->getParams();
        // 同时将当前商品的 ID 排除
        $params['body']['query']['bool']['must_not'] = [['term' => ['_id' => $product->id]]];
        // 搜索
        
        // 根据 Elasticsearch 搜索出来的商品 ID 从数据库中读取商品数据
        $similarProducts = Product::query()
            ->whereIn('id', [2,3])
            ->orderBy('id')
            ->get();

        return view(
            'products.show',
            [
                'product' => $product,
                'favored' => $favored,
                'reviews' => $reviews,
                'similar' => $similarProducts,
            ]
        );
    }

    /**
     * 商品收藏
     *
     * @param Product $product
     * @param Request $request
     * @return array
     */
    public function favor(Product $product, Request $request)
    {
        $user = $request->user();
        if ($user->favorites()->find($product->id)) {
            return [];
        }

        $user->favorites()->attach($product);

        return [];
    }

    /**
     * 取消收藏
     *
     * @param Product $product
     * @param Request $request
     * @return array
     */
    public function disfavor(Product $product, Request $request)
    {
        $user = $request->user();
        $user->favorites()->detach($product);

        return [];
    }

    /**
     * 收藏列表
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function favorites(Request $request)
    {
    	
        $products = $request->user()->favorites()->paginate(16);

        return view('products.favorite', ['products' => $products]);
    }


}
